﻿using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;

namespace Rio.Manager.Application.Utils.Validation
{
    public class ValidationScope
    {
        #region Fields

        public static readonly DependencyProperty ErrorsProperty = 
            DependencyProperty.RegisterAttached("Errors", typeof(IList<ValidationError>), typeof(ValidationScope),
            new PropertyMetadata(null, ErrorsChanged));

        #endregion Fields

        #region Methods

        public static void ErrorsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            FrameworkElement element = (FrameworkElement)obj;
            element.BindingValidationError += delegate(object sender, ValidationErrorEventArgs e)
            {
                if (e.Action == ValidationErrorEventAction.Added)
                {
                    GetErrors(obj).Add(e.Error);
                }
                else
                {
                    GetErrors(obj).Remove(e.Error);
                }
            };
        }

        public static IList<ValidationError> GetErrors(DependencyObject obj)
        {
            return (IList<ValidationError>)obj.GetValue(ErrorsProperty);
        }

        public static void SetErrors(DependencyObject obj, IList<ValidationError> value)
        {
            obj.SetValue(ErrorsProperty, value);
        }

        #endregion Methods
    }
}